<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\SystemGroup;
use App\Models\SystemGroupData;
use App\Traits\Controllers\AdminTraits;
use App\Transformers\System\SystemGroupDataTransformer;
use Illuminate\Http\Request;

class SystemGroupDataController extends Controller
{
    use AdminTraits;

    public $model = SystemGroupData::class;
    public $transformer = SystemGroupDataTransformer::class;

    public function index(Request $request,$id)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);

        $table = SystemGroup::query()
            ->select('fields')
            ->find($id);

        $data = $this
            ->getQuery()
            ->pimp()//自动转换where条件
            ->where('group_id',$id)
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer))->meta('fields',$table['fields']);
    }

    public function show(Request $request, $id)
    {
        $show = $this->getQuery()->findOrFail($request->data);// findOrFail 查找失败时抛出异常404

        if ($this->policy) {
            $this->authorize('show', $show);
        }

        $table = SystemGroup::query()
            ->select('fields')
            ->find($id);

        return $this->response->item($show, resolve($this->transformer))->meta('fields',$table['fields']);
    }

    public function update(Request $request)
    {
        //验证用户凭证信息
        $this->validateData($request);

        $data = $this->getQuery()->findOrFail($request->data);

        if ($this->policy) {
            $this->authorize('update', $data);
        }

        $data->fill($request->all());
        $data->save();

        return $this->response->noContent();
    }

    public function destroy(Request $request)
    {
        $ids = array_filter(explode(',', $request->data));

        if (empty($ids)) {
            return $this->response->errorBadRequest();
        }
        $this->getQuery()->whereIn($this->getQuery()->getKeyName(), $ids)->delete();

        return $this->response->noContent();
    }

    /**
     * 状态禁用和启用
     */
    public function status(SystemGroupData $data)
    {
        $data->status = $data->status == 0 ? 1 : 0;
        $data->save();

        return $this->response->noContent();
    }

    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'PUT':
            case 'PATCH':
            case 'POST':
                return [
                    'group_id' => 'required',
                    'value' => 'required'
                ];
                break;

        }
        return [];
    }

    /**
     * 字段
     *
     * @return array
     */
    public function customAttributes(): array
    {
        return [
            'group_id' => '组合分类id',
            'value' => '数据组对应的数据值'
        ];
    }
}
